package com.liuyucheng.interview.threadlocal;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 内存泄漏的示例
 */
public class ThreadLocalMemoryLeak {
    private static final ThreadLocal<List<Object>> threadLocal = new ThreadLocal<>();

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(1);

        // 提交任务：向ThreadLocal存储大对象
        executor.submit(() -> {
            threadLocal.set(new ArrayList<>(1000));
            System.out.println("Task completed.");
            // 未调用threadLocal.remove()
//            threadLocal.remove();
        });

        // 模拟ThreadLocal实例被回收
        executor.submit(() -> {
            System.out.println("Second task running.");
            // 此时第一个任务的ThreadLocal已无外部引用，但value仍未释放
        });

        Thread.sleep(1000);
        executor.shutdown();
    }
}